<include file="../header" />
</head>
<body class="J_scroll_fixed">
<script type="text/javascript">

    function onlyNumber(obj){
        //得到第一个字符是否为负号
        var t = obj.value.charAt(0);
        //先把非数字的都替换掉，除了数字和.
        if(obj.value != 0)
        obj.value = obj.value.replace(/[^\d\.]/g,'').replace(/^0{1,}/g,'');
        //必须保证第一个为数字而不是.
        obj.value = obj.value.replace(/^\./g,'');
        //保证只有出现一个.而没有多个.
        obj.value = obj.value.replace(/\.{2,}/g,'.');
        //保证.只出现一次，而不能出现两次以上
        obj.value = obj.value.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
        //只能输入两位小数
        obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');
        //如果第一位是负号，则允许添加
        if(t == '-'){
            return;
        }

        var index = obj.name.substring(obj.name.indexOf("_") + 1, obj.name.length);
        var numberName = "number_" + index;
        var number = $("input[name="+numberName+"]").val();
        var priceName = "price_" + index;
        var price = $("input[name="+priceName+"]").val();
        var totalPriceName = "total_price_" + index;
        $("input[name="+totalPriceName+"]").val(price*number);
    }

    function insertRows(codeArr){
        //获取表格对象
        var tb1 = $("#viewTabs");                // 找table的ID
        var rowNum= $("#viewTabs tr").size();  //获取表格的行数
        //var liNum=$("tr[id^='_tr_']").size();  //获取以_tr_开头测tr个数
        var tempRow=rowNum-1; //用于新增tr、td、属性下标
        if(codeArr == null){
            var finishedProduct = $("select[name=finishedProductId]").val();
            codeArr = finishedProduct.split(",");
            var finishedProductId = codeArr[0];
            var name = codeArr[1];
            var className = codeArr[2];
//        var size = codeArr[3];
            var size = $("select[name=size]").val();
            var unit = codeArr[4];
            var barcode = codeArr[5];
            var supplierId = codeArr[6];
            var supplierName = codeArr[9];
            var imageUrl = codeArr[7];
            var batchNo = "";
            var number = "";
            var price = "";
            var totalPrice = "";
            var productionDate = "";
            var expiryDate = "";
        }else{
            var finishedProductId = codeArr["finished_product_id"];
            var name = codeArr["name"];
            var className = codeArr["class_name"];
            var size = codeArr["size"];
            var unit = codeArr["unit"];
            var barcode = codeArr["barcode"];
            var supplierId = codeArr["supplier_id"];
            var supplierName = codeArr["supplier_name"];
            var imageUrl = codeArr["image_url"];
            var batchNo = codeArr["batch_no"];
            var number = codeArr["number"];
            var price = codeArr["price"];
            var totalPrice = codeArr["total_price"];
            var productionDate = codeArr["production_date"];
            var expiryDate = codeArr["expiry_date"];
        }


//        var codeName = $("select[name=codeId]").find("option:selected").text();

        var $td0 = $("<td></td>");
        $td0.html("<img style='width:40px;' src='"+imageUrl+"'><input type=\'hidden\' class=\'input\' name=\'finished_product_id_"+tempRow+"\' value=\'"+finishedProductId+"\'/>");

        var $td1 = $("<td></td>"); //创建第一个td
        $td1.html("<a style='color: #1cc385;'>" +name + "</a><br/>[ " + size +" ] <input type=\'hidden\' class=\'input\' name=\'size_"+tempRow+"\' value=\'"+size+"\'/>"); //html把序号放到了第一个td里面

        var $td2 = $("<td></td>");
        $td2.html(className + "<br/>" +"[ " + supplierName +" ] <input type=\'hidden\' class=\'input\' name=\'supplier_id_"+tempRow+"\' value=\'"+supplierId+"\'/>");

        var $td3 = $("<td></td>");
        $td3.html("<input type=\'text\' class=\'input batchNo\' name=\'batch_no_"+tempRow+"\' value=\'"+batchNo+"\'/>");

        var $td4 = $("<td></td>");
        $td4.html("<input type=\'text\' class=\'input number\' name=\'number_"+tempRow+"\' onkeyup=\'onlyNumber(this)\' value=\'"+number+"\'/>");

        var $td5 = $("<td></td>");
        $td5.html(unit);

        var $td6 = $("<td></td>");
        $td6.html("<input type=\'text\' class=\'input price\' name=\'price_"+tempRow+"\' onkeyup=\'onlyNumber(this)\' value=\'"+price+"\'/>");

        var $td7 = $("<td></td>");
        $td7.html("<input autocomplete=\'off\' type=\'text\' class=\'input J_date1\' style=\'width: 100px\' name=\'production_date_"+tempRow+"\' value=\'"+productionDate+"\'/>");

        var $td8 = $("<td></td>");
        $td8.html("<input autocomplete=\'off\' type=\'text\' class=\'input J_date1\' style=\'width: 100px\' name=\'expiry_date_"+tempRow+"\' value=\'"+expiryDate+"\'/>");

        var $td9 = $("<td></td>");
        $td9.html(barcode);

        var $td10 = $("<td></td>");
        $td10.html("<input type=\'text\' class=\'input totalPrice\' name=\'total_price_"+tempRow+"\' value=\'"+totalPrice+"\' readonly/>");

        var $td11 = $("<td></td>");
        $td11.html("<a class=\'btn btn-danger btn-del\'> 移除</a>");

        var $tr = $("<tr id=\'_tr_"+tempRow+"\' class=\'in-opt\'></tr>");// 创建tr，将3个td放置到tr中
        $tr.append($td0);
        $tr.append($td1);
        $tr.append($td2);
        $tr.append($td3);
        $tr.append($td4);
        $tr.append($td5);
        $tr.append($td6);
        $tr.append($td7);
        $tr.append($td8);
        $tr.append($td9);
        $tr.append($td10);
        $tr.append($td11);
        //在表格的最后追加新增的tr
        tb1.append($tr);

        var dateInput = $("input.J_date1")
        if (dateInput.length) {
            Wind.use('datePicker', function () {
                dateInput.datePicker();
            });
        }

        $("select[name='size']").find("option").eq(0).prop("selected",true);
        $(".addRow").hide();
        var row = $("input[name=row]").val();
        $("input[name=row]").val(parseInt(row)+1);
    }

    $(function() {

        $(".search").click(function() {
            $(".addRow").hide();
            $(".sizeList").hide();
            $("select[name=finishedProductId]").empty();
            $("select[name=finishedProductId]").append("<option value='0'></option>");
            var name = $("input[name=name]").val().toLowerCase();
            var listArr=<?php echo json_encode($listFinishedProduct);?>;
            var count = 0;
            var list=eval(listArr);
            var classId = $("select[name=classId]").val();
            for(var i=0;i<list.length;i++){
                if(classId > 0 && list[i]["class_id"] != classId){
                    continue;
                }
                if(list[i]["name"].toLowerCase().indexOf(name) != -1){
                    var val = list[i]["finished_product_id"] + "," + list[i]["name"] + "," + list[i]["class_name"] + "," + list[i]["size"] + "," + list[i]["unit"] + "," + list[i]["barcode"] + "," + list[i]["supplier_id"]+ "," + list[i]["image_url"]+ "," + list[i]["size_detail"]+ "," + list[i]["supplier_name"];
                    $("select[name=finishedProductId]").append("<option value='"+val+"'>["+list[i]["class_name"]+"] "+list[i]["name"]+"</option>");
                    count++;
                }
            }
            if(count>0){
                $(".nameList").show();
                $("select[name=finishedProductId]").focus();
            }else{
                $(".nameList").hide();
            }
        });

        $("select[name='finishedProductId']").change(function () {
            $(".addRow").hide();
            $(".sizeList").hide();
            $("select[name=size]").empty();
            $("select[name=size]").append("<option value='0'></option>");
            var finishedProduct = $("select[name=finishedProductId]").val();
            var codeArr = finishedProduct.split(",");
            var size = codeArr[3];
            var sizeDetail = codeArr[8];
            var sizeArr = size.split("/");
            var sizeDetailArr = sizeDetail.split("/");
            var count = 0;
            for(var i=0;i<sizeArr.length;i++){
                $("select[name=size]").append("<option value='"+sizeArr[i]+"'>"+sizeArr[i]+" ( "+sizeDetailArr[i] +"）</option>");
                count++;
            }
            if(count>0){
                $(".sizeList").show();
                $("select[name=size]").focus();
            }else{
                $(".sizeList").hide();
            }
        });

        $("select[name='size']").change(function () {
            if($("select[name='size']").val() != ""){
                $(".addRow").show();
            }
        });

        $("button.btn_submit").click(function() {

           if($("#viewTabs tr").size() == 1){
                alert("请增加成品矫形器订单");
                $("input[name=codeName]").focus();
                return false;
            }

            if ($("select[name=store_id]").val() == 0) {
                alert("请选择【收货仓】");
                $("select[name=store_id]").focus();
                return false;
            }

            if ($("input[name=purchase_date]").val() == 0) {
                alert("请选择【采购时间】");
                $("input[name=purchase_date]").focus();
                return false;
            }

            if (confirm("提交采购入库将无法再次修改，是否继续提交")) {
                $("button.btn_submit").hide();
            } else {
                return false;
            }

        });

            $("#viewTabs").on('click', '.btn-del', function () {
            $(this).closest('tr').remove();
        });

        $(document).off('change','#upload').on('change','#upload',function(){
            //上传文件
            $(".top").hide();
            $(".word").show();
            var url = "{:U('activity/uploadExcel?className=PurchaseFinishedProduct&importType=1')}";
            $.ajaxFileUpload({
                url:url,//处理图片脚本
                secureuri :false,
                fileElementId :'upload',//file控件id
                dataType : 'json',
                success : function (data, status){
//                    alert(data.message);
//                    alert(data.purchase_no);
                    $(".top").show();
                    $(".word").hide();
                    $("input#upload").val("");

                    var codeArr;
                    var count = 0;
                    var invalid = 0;
                    for(var i=0;;i++) {
                        if(typeof data[i] == "undefined"){
                            invalid++;
                            break;
                        }
                        var listArr=<?php echo json_encode($listFinishedProduct);?>;

                        var list=eval(listArr);
                        for(var j=0;j<list.length;j++){
                            if(list[j]["finished_product_id"] == data[i].finished_product_id){
                                codeArr = list[j];
                                codeArr["size"] = data[i].size;
                                codeArr["batch_no"] = data[i].batch_no;
                                codeArr["number"] = data[i].number;
                                codeArr["price"] = data[i].price;
                                codeArr["total_price"] = data[i].total_price;
                                codeArr["production_date"] = data[i].production_date;
                                codeArr["expiry_date"] = data[i].expiry_date;
                                insertRows(codeArr);
                                count++;
                                break;
                            }
                        }
                    }

                    alert("成功读取 " + count + " 条；无效数据 " + invalid + " 条。");
                },
                error: function(data, status, e){
                    alert(e);
                    $(".top").show();
                    $(".word").hide();
                    $("input#upload").val("");
                }
            })

        });
    });

</script>
<style type="text/css">
    .btn,.btn-danger,.btn-info,.btn-success,.btn-warning{
        width: 50px;
        /*height: 18px;*/
        padding: 2px 0px 2px 0px;
        margin: 1px 0px 1px 0px;
    }
    .top {
        height: 25px;
        width: 120px;
        background-color: #1dccaa;
        line-height: 25px;
        cursor: pointer;
        display: inline-block;
        text-align: center;
        color: #fff;
        border-radius: 3px;
    }
    .code{
        width: 150px;
    }
    .batchNo{
        width: 150px;
    }
    .number{
        width: 40px;
    }
    .price{
        width: 50px;
    }
    .J_date{
        width: 100px;
    }
    .totalPrice{
        width: 60px;
    }
</style>
<div class="wrap jj">
    <div class="common-form">
        <form method="post" class="form-horizontal J_ajaxForm" action="{:U('Purchase/purchaseFinishedProductPost')}">
            <a style="color:#45a1de;font-weight: bold;font-size: large">成品矫形器采购入库单</a>
            &nbsp;&nbsp;&nbsp;
            <if condition="$info['status'] eq '1'">
                <a style="color: #1cc385;font-weight: bold;font-size: large">（已审核）</a>
            </if>
            <if condition="$info['status'] eq '-1'">
                <a style="color: #ed7667;font-weight: bold;font-size: large">（未审核）</a>
            </if>
            <if condition="$info['status'] eq '-2'">
                <a style="color: #ed7667;font-weight: bold;font-size: large">（已反审核）</a>
            </if>
            <br/><br/>
            <input type="hidden" name="id" value="{$info.purchase_id}" />
            <fieldset>
                <div class="control-group">
                    单号：<input type="text" name="purchase_no" value="{$info.purchase_no}" readonly/>
                    &nbsp;&nbsp;&nbsp;
                    收货仓：
                    <select name="store_id" style="width: auto">
                        {:getCommonSelectOptionHtml($info['store_id'], "Store", "store_id", "store_name", null, $user['enterprise_code'], 1)}
                    </select>
                    &nbsp;&nbsp;&nbsp;&nbsp;
                    <!--供应商：
                    <select name="supplier_id">
                        {:getCommonSelectOptionHtml($info['supplier_id'], "Supplier", "supplier_id", "supplier_name", null, $user['enterprise_code'], 1)}
                    </select>-->
                    <br/><br/>
                    备注：
                    <input type="text" class="input" style="width: 790px" name="remark" value="{$info.remark}">
                </div>
                <hr class="half-rule">

                <if condition="$info['status'] eq null">
                    <div class="control-group">
                        数据：
                        <!--select name="import_store_id" style="width: auto">
                            {:getCommonSelectOptionHtml($store_id, "Store", "store_id", "store_name", null, $user['enterprise_code'], 1, "选择仓库")}
                        </select-->
                        &nbsp;&nbsp;
                        <label for="upload" class="top">读取Excel文件</label>
                        <span class="word" style="color: #de7d74; display: none">读取中。。。</span>
                        <input type="file" multiple id="upload" style="display: none;" name="fileToUpload" accept=".xls,.xlsx,.csv"/>
                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        模板文件：
                        <a style="color:#45a1de; font-size: medium; text-decoration:underline;" href="https://xwk-file.oss-cn-qingdao.aliyuncs.com/Home/成品采购导入模板.xlsx">下载【成品矫形器采购】Excel模板</a>
                    </div>
                    <hr class="half-rule">
                </if>
                <table class="table table-hover table-bordered" id="viewTabs">
                    <thead>
                        <tr>
                            <th style="min-width: 50px; width: 50px">缩略图</th>
                            <th style="width: 200px">名称 [ 规格 ]</th>
                            <th style="width: 130px">分类 [供应商]</th>
                            <th style="width: 50px">批号</th>
                            <th style="min-width: 40px; width: 40px">数量</th>
                            <th style="min-width: 40px; width: 40px">单位</th>
                            <th style="min-width: 85px; width: 85px">单价</th>
                            <th style="width: 100px">生产日期</th>
                            <th style="width: 100px">有效期至</th>
                            <th style="">条形码</th>
                            <th style="min-width: 100px; width: 100px">金额</th>
                            <th style="min-width: 50px; width: 50px">操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <foreach name="list" item="vo" key="k">
                            <tr>
                                <td>
                                    <img src="{$vo.image_url}" style="width:40px;">
                                    <input type="hidden" class="input" name="finished_product_id_{$k}" value="{$vo.finished_product_id}" >
                                    <input type="hidden" class="input" name="purchase_finished_product_id_{$k}" value="{$vo.purchase_finished_product_id}" >
                                </td>
                                <td>
                                    <a style="color: #1cc385;">{$vo.name}</a><br/>[ {$vo.size} ]
                                    <input type="hidden" class="input" name="size_{$k}" value="{$vo.size}">
                                </td>
                                <td>
                                    {$vo.class_name}<br/>[ {$vo.supplier_name} ]
                                    <input type="hidden" class="input" name="supplier_id_{$k}" value="{$vo.supplier_id}">
                                </td>
                                <td><input type="text" class="input batchNo" name="batch_no_{$k}" value="{$vo.batch_no}"></td>
                                <td><input type="text" class="input number" name="number_{$k}" value="{$vo.number}" onkeyup="onlyNumber(this)"></td>
                                <td>{$vo.unit}</td>
                                <td><input type="text" class="input price" name="price_{$k}" value="{$vo.price}" onkeyup="onlyNumber(this)">&nbsp;元</td>
                                <td><input type="text" class="input J_date" name="production_date_{$k}" value="{$vo.production_date}" autocomplete="off"></td>
                                <td><input type="text" class="input J_date" name="expiry_date_{$k}" value="{$vo.expiry_date}" autocomplete="off"></td>
                                <td>{$vo.barcode}</td>
                                <td><input type="text" class="input totalPrice" name="total_price_{$k}" value="{$vo.total_price}" readonly>&nbsp;元</td>
                                <if condition="$info['status'] neq '1' && $info['status'] neq '-1'">
                                    <td>
                                        <a class="btn btn-danger btn-del">移除</a>
                                    </td>
                                </if>
                            </tr>
                        </foreach>
                    </tbody>
                </table>

                <if condition="$info['status'] neq '1' && $info['status'] neq '-1'">
                    <div class="control-group">
                        类型：
                        <select style="width: 120px" name="classId">
                            {:getClassSelectOptionHtml(null, 1, $user['enterprise_code'])}
                        </select>
                        &nbsp;&nbsp;
                        名称搜索：
                        <input type="text" class="input" name="name" value="">
                        <a class="btn btn-info search">搜索</a>
                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        <div class="nameList" style="color: #1cc385;display: none;margin-left: 183px">
                            成品矫形器列表：
                            <select style="width: auto" name="finishedProductId">
                                <option value='0'></option>
                            </select>
                        </div>
                        <div class="sizeList" style="color: #1cc385;display: none;margin-left: 183px">
                            规格列表：
                            <select style="width: auto" name="size">
                                <option value='0'></option>
                            </select>
                            <a class="btn btn-success addRow" onclick='javascript:insertRows()' style="display: none">添加</a>
                        </div>

                    </div>
                </if>

                <input type="hidden" name="row" value="{$row}"/>
                <hr class="half-rule">
                <div class="control-group">
                    采购时间：
                    <input type="text" class="input J_date" style="width: 150px" name="purchase_date" value="{$info.purchase_date}" autocomplete="off">
                    &nbsp;&nbsp;&nbsp;
                    操作人：</label>
                    <select readonly>
                        {:getCommonSelectOptionHtml($info['update_id'], "Admin", "employee_id", "admin_name", null, $user['enterprise_code'], 1)}
                    </select>
                    <!--<img style="height: 50px" src="{$info.p127}">-->
                </div>
                <div class="control-group" style="display: none">
                    <div class="controls">
                        <label class="checkbox inline" style="font-weight: bold">
                            <input type="checkbox"  name="completed" checked>完成 （勾选后提交流程将无法再次修改）
                        </label>
                    </div>
                </div>

            </fieldset>
            <div class="form-actions">
                <php>
                    $btnText = "入库";
                    $btnStatus = -1;
                    $role = explode(',',$user["role"]);
                    if(in_role($role,"8")){
                        if($info["status"] == -2 || isNullOrEmpty($info["status"])){
                            $btnText = "入库";
                            $btnStatus = 1;
                        }else{
                            $btnText = "已入库";
                            $btnStatus = -1;
                        }
                    }
                    if(in_role($role,"4")){
                        if($info["status"] == -1){
                            $btnText = "审核";
                            $btnStatus = 1;
                        }
                        if($info["status"] == 1){
                            $btnText = "反审核";
                            $btnStatus = 1;
                        }
                    }
                </php>
                <if condition="$btnStatus eq 1">
                    <button type="submit" style="width: 70px" class="btn btn-primary btn_submit ">{$btnText}</button>
                    <else/>
                    <button disabled="disable" style="background-color: #93949c; width: 70px" class="btn btn-primary btn_submit">{$btnText}</button>
                </if>
                <input type="hidden" name="btnText" value="{$btnText}"/>
                <a style="width: 70px" class="btn" href="__URL__">返回</a>
            </div>
        </form>
    </div>
</div>
<script src="__ROOT__/statics/js/common.js"></script>
</body>
</html>